import React from 'react'
import { connect } from 'react-redux'
import { Form, Select, Input, Row, Col, InputNumber, Spin, message, Button, Alert, Icon, Popover } from "antd";
import "styles/loan-billing/repayment-content.scss"
import { messages, deepFullCopy } from "share/common";
import ImageUpload from 'components/image-upload';
import moment from 'moment';
import bankBillListService from './bank-bill-list.service'
const FormItem = Form.Item;
const Option = Select.Option;
const { TextArea } = Input;
const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 14, offset: 1 }
};

class NewRepayment extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      info: {},
      paymentType: 'cash',
      repayAttachment: [],
      repayAttachmentImages: [],
      loading: false,
      loanRefund: false,
      printLoading: false,
      allSelectedRecords: []
    }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.repayFrame === this.props.repayFrame)
      return;
    if (!nextProps.repayFrame) {
      this.props.form.resetFields();
      this.setState({
        info: {},
        repayAttachment: [],
        repayAttachmentImages: [],
        loanRefund: false,
        allSelectedRecords: []
      });
      return !1;
    }
    this.props.form.resetFields();
    const { isOldCompany } = this.props;
    this.setState({
      info: nextProps.info,
      loanRefund: nextProps.loanRefund,
      allSelectedRecords: nextProps.allSelectedRecords
    })
  };

  /**
   * 格式化数字
   * @param {Number} nStr 数字
   */
  addCommas = (nStr) => {
    nStr = nStr + '';
    let x = nStr.split('.');
    let x1 = x[0];
    let x2 = x.length > 1 ? '.' + x[1] : '';
    let rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
      x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
  }

  //获取上传图片的OId
  getUploadImageOId = (values) => {
    let repayAttachment = [];
    values.map(item => {
      repayAttachment.push({ attachmentOID: item.attachmentOID })
    });
    this.setState({ repayAttachment, repayAttachmentImages: values })
  };

  /**
   * 提交还款单
   * @param {Boolean} isNeedPrint 是否需要打印
   */
  handleSave = async (isNeedPrint = false) => {
    this.props.form.validateFieldsAndScroll(async (err, values) => {
      if (!err) {
        let repayAttachmentOids = this.state.repayAttachment.map((item) => item.attachmentOID)
        let paramsBody = {
          ids: this.props.params.params.ids,
          relations: this.props.params.params.relations,
          repayAttachmentOids: repayAttachmentOids,
          remark: values.remark
        }
        const { agentOid } = this.props.params;
        let paramsUrl = {
          print: isNeedPrint,
          companyName: '金拱门(中国)有限公司(公司编码:104)',
          accountName: '金拱门(中国)有限公司',
        }
        if (agentOid) {
          paramsUrl.userOid = agentOid;
        }
        this.setState({
          loading: true
        }, async () => {
          let res = await bankBillListService.toBorrow(paramsBody, paramsUrl)
          if (res.status === 200) {
            message.success('操作成功')
            this.setState({ loading: false })
            this.props.submitFun()
          } else {
            console.error(res)
            this.setState({ loading: false })
            message.error('操作失败，请重新操作。')
          }
        })
      }
    })
  };

  hanldeOnViewDetails = (record, index) => {
    let tempRecords = deepFullCopy(this.state.allSelectedRecords)
    if (tempRecords[index].id === record.id) {
      if (tempRecords[index].selectedRelationList && tempRecords[index].selectedRelationList.length > 0) {
        tempRecords[index].showDetails = !record.showDetails
      }
    } else {
      tempRecords.some((item, i) => {
        if (item.id === record.id) {
          if (tempRecords[i].selectedRelationList && tempRecords[i].selectedRelationList.length > 0) {
            tempRecords[i].showDetails = !record.showDetails
            return true
          }
        }
      })
    }
    this.setState({
      allSelectedRecords: tempRecords
    })
  }

  render() {
    const {
      info,
      paymentType,
      repayAttachmentImages,
      loading,
      loanRefund,
      printLoading,
      allSelectedRecords } = this.state;
    const { getFieldDecorator } = this.props.form;
    let showData = false;
    return (
      <div className='new-repayment-frame'>
        {
          !loanRefund && <Alert type='warning' showIcon message={messages('loan-billing.key154')/*还款单提交后，还需财务复核方可生效*/} />
        }
        <Form>
          <div className='title'>{messages('loan-billing.key72')/*还款方信息*/}</div>
          <Row>
            <Col span={6} className="form-define-title">{messages('loan-billing.key7')/*还款金额*/}：</Col>
            <Col span={3} offset={1}>
              <FormItem>
                {getFieldDecorator('curreny', {
                  initialValue: this.props.posCurCod
                })(
                  <Input disabled />
                )}
              </FormItem>
            </Col>
            <Col span={5}>
              <FormItem>
                {getFieldDecorator('repaymentValue', {
                  rules: [],
                  initialValue: this.addCommas(Number(this.props.total || '0').toFixed(2))
                })(
                  <Input
                    min={0}
                    className="input-number"
                    disabled
                  />
                )}
              </FormItem>
            </Col>
          </Row>
          <FormItem {...formItemLayout} label={messages('loan-billing.key3')/*还款方式*/} className={'paymentType-select'}>
            {getFieldDecorator('paymentType', {
              rules: [],
              initialValue: 'online'
            })(
              <Select
                disabled
                getPopupContainer={() => document.getElementsByClassName('paymentType-select')[0]}
              >
                <Option key={'online'} value={'online'}>转账还款</Option>
              </Select>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('common.remark')/*备注*/}>
            {getFieldDecorator('remark', {
              rules: [{
                required: true,
                message: messages('common.enter')
              }],
              initialValue: '公务卡转因私'
            })(
              <TextArea
                rows={4}
                style={{ width: '100%', resize: 'none' }}
                maxLength="200"
                disabled
                placeholder={
                  `${messages("common.please.enter")}, ${messages("common.max.characters.length", { max: 200 })}`
                }
              />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={`${messages('loan-billing.key79')/*流水转账凭证*/}（${messages('common.max.image.length', { max: 3 })}）`}>
            {getFieldDecorator('repayAttachment', {
              rules: [{
                required: true,
                message: messages('common.please.select')
              }],
              initialValue: []
            })(
              <ImageUpload
                attachmentType="REPAYMENT_IMAGES"
                defaultFileList={repayAttachmentImages}
                fileType={["PNG", 'png', 'JEPG', 'jepg', 'jpg', 'JPG', 'bmp', 'BMP', "jpg", "JPG", "jpeg", "JPEG"]}
                isShowDefault
                maxNum={3}
                onChange={this.getUploadImageOId} />
            )}
          </FormItem>
          <div>
            <div className="title"> {messages('loan-billing.key80')/* 收款方信息 */}
              <span>{messages('loan-billing.key81')/* 请按以下收款方账号打款 */}</span>
            </div>
            <FormItem {...formItemLayout} label={messages('loan-billing.key186')/* 开户公司 */} className="accept-account-container">
              {getFieldDecorator('companyName', {
                rules: [],
                initialValue: '104'
              })(
                <Select disabled placeholder={messages('common.please.select')}>
                  <Option key={'104'} value={'104'}>金拱门(中国)有限公司</Option>
                </Select>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label={messages('loan-billing.key76')/*开户账号*/}>
              {getFieldDecorator('acceptAccount', {
                initialValue: '2116 8111 4610 001'
              })(
                <Input disabled />
              )}
            </FormItem>
            <FormItem {...formItemLayout} label={messages('loan-billing.key188')/*账号名称*/}>
              {getFieldDecorator('accountName', {
                initialValue: '金拱门(中国)有限公司'
              })(
                <Input disabled />
              )}
            </FormItem>
            <FormItem {...formItemLayout} label={messages('loan-billing.key77')/*开户银行*/}>
              {getFieldDecorator('acceptBankName', {
                initialValue: '招商银行股份有限公司上海苏河湾支行'
              })(
                <Input disabled />
              )}
            </FormItem>
          </div>
          <div>
            <div className="title"> {messages('mcd.myAccount.publicServiceCardBankBill.details')/* 公务卡消费明细 */}</div>
            <div className="detailsContainer" style={{ padding: '0px' }}>
              {allSelectedRecords.map((record, index) => {
                if (record.selectedRelationList && record.selectedRelationList.length > 0) {
                  let total = 0
                  let oriTotal = 0
                  record.selectedRelationList.map((item) => {
                    if (Number(item.amount) !== NaN) {
                      total = total + item.amount
                    }
                    if (Number(item.oriAmount) !== NaN) {
                      oriTotal = oriTotal + item.oriAmount
                    }
                  })
                  return (
                    record.selectedRelationList.length > 0 && <div className={'detailBlock'}>
                      <div style={{ fontSize: '12px', height: '75px', lineHeight: '25px' }} className={'detailHead'}>
                        <span>交易金额：</span>
                        <span className={'headText'}>{record.oriCurCod} </span>
                        <span className={'headText'}>{this.addCommas(Number(record.oriCurAmt || '0').toFixed(2))}</span>
                        <span style={{ marginRight: '4px' }}>|</span>
                        <span>入账金额：</span>
                        <span className={'headText'}>{record.posCurCod} </span>
                        <span className={'headText'}>{this.addCommas(Number(record.posCurAmt || '0').toFixed(2))}</span>
                        <br/>
                        {/* <span className={'headText'}>交易金额：</span>
                        <span className={'headText'}>{record.oriCurCod} </span>
                        <span className={'headText'}>{this.addCommas(Number(record.oriAssociatedAmt || '0').toFixed(2))}</span>
                        <span style={{ marginRight: '4px' }}>|</span>
                        <span>已处理金额：</span>
                        <span className={'headText'}>{record.posCurCod} </span>
                        <span className={'headText'}>{this.addCommas(Number(record.associatedAmt || '0').toFixed(2))}</span>
                        <br/> */}
                        <Popover content={record.acpName} placement={'topLeft'}>
                          <div
                            style={{
                              height: '25px',
                              width: '100%',
                              overflow: 'hidden',
                              whiteSpace: 'nowrap',
                              textOverflow: 'ellipsis',
                              marginBottom: '-25px'
                            }}
                          >
                            <span className={'headText'}>{messages('mcd.myAccount.publicServiceCardBankBill.acpName')}：</span>
                            <span className={'headText'}>{record.acpName}</span>
                          </div>
                        </Popover>
                        <br/>
                        <span className={'headText'}>交易日期：</span>
                        <span className={'headText'}>{record.trsDate && record.trsDate.length > 0 ? moment(record.trsDate).format('YYYY-MM-DD') : '-'}</span>
                      </div>
                      <div className={'detailContent'} style={{ paddingBottom: record.showDetails && '0px' }}>
                        <div style={{ height: '20px' }} className={'contentHead'}>
                          <span className={'contentHeadText'}>{messages('mcd.myAccount.publicServiceCardBankBill.relationsTotal')}：</span>
                          <span className={'contentHeadText'}>{record.oriCurCod}</span>
                          <span className={'contentHeadText'}>{this.addCommas(Number(oriTotal || '0').toFixed(2))}</span>
                          <span style={{ marginRight: '4px' }}>/</span>
                          <span className={'contentHeadText'}>{record.posCurCod}</span>
                          <span className={'contentHeadText'}>{this.addCommas(Number(total || '0').toFixed(2))}</span>
                          {(record.selectedRelationList && record.selectedRelationList.length > 0) ? record.showDetails ?
                            <Icon
                              onClick={() => this.hanldeOnViewDetails(record, index)}
                              className={'viewDetails'}
                              style={{ verticalAlign: 'middle' }}
                              type="up-circle-o"
                            /> :
                            <Icon
                              onClick={() => this.hanldeOnViewDetails(record, index)}
                              className={'viewDetails'}
                              style={{ verticalAlign: 'middle' }}
                              type="down-circle-o"
                            /> : null}
                          {(record.selectedRelationList && record.selectedRelationList.length > 0) ?
                            <span
                              onClick={() => this.hanldeOnViewDetails(record, index)}
                              className={'viewDetails'}
                            >
                              {messages('mcd.myAccount.publicServiceCardBankBill.viewDetails')}
                            </span> : null
                          }
                        </div>
                        {record.showDetails && record.selectedRelationList.map((relation) => (
                          <div className={'detailLine'}>
                            <div className={'part'}>
                              <span className={'label'}>{messages('mcd.myAccount.publicServiceCardBankBill.splitAmt')}: </span>
                              <span className={'value'}>{record.oriCurCod} </span>
                              <span className={'value'}>{this.addCommas(Number(relation.oriAmount || '0').toFixed(2))}</span>
                            </div>
                            <div className={'part'}>
                              <span className={'label'}>入账金额: </span>
                              <span className={'value'}>{record.posCurCod} </span>
                              <span className={'value'}>{this.addCommas(Number(relation.amount || '0').toFixed(2))}</span>
                            </div>
                            <div className={'part'}>
                              <span className={'label'}>状态: </span>
                              <span className={'value status'}>{relation.status}</span>
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>
                  )
                }
              })}
            </div>
          </div>
          
        </Form>
        <div className="footer-operate" style={{ backgroundColor: '#ffffff', left: '0px', marginRight: '10px' }}>
          <Button type="primary" onClick={() => this.handleSave()} loading={loading}>
            {loanRefund ? messages('loan-billing.key83')/*确认*/ : messages('common.submit')/*提交*/}
          </Button>
          {showData && <Button onClick={() => this.handleSave(true)} loading={printLoading} style={{ margin: '0px 10px' }}>
            {loanRefund ? messages('loan-billing.key155')/*确认并打印*/ : messages('loan-billing.key156')/*提交并打印*/}
          </Button>}
          <Button onClick={() => { this.props.closeFun() }}>{messages('common.cancel')}</Button>
        </div>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
    isOldCompany: state.login.isOldCompany
  }
}

const WrappedEditLoan = Form.create()(NewRepayment);

export default connect(mapStateToProps)(WrappedEditLoan);
